//
// Created by hongyu on 2021/11/21.
//

#include "../include/json.hpp"
#include "../../platform/include/platform.hpp"

json::json(const char* n): file_attr(n){
    fp = fopen(name,"r");
    buffer = (char*)calloc(this->size(),1);
    fread(buffer,this->size(),1,fp);
    root = cJSON_Parse(buffer);
}

json::~json() {
    cJSON_Delete(root);
    free(buffer);
    buffer = nullptr;
}

void json::print() {
     printp("Json:\t\n");
     printp("%s\n",buffer);
}

void json::find(const char *node, std::string & value) {
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    if(ptr != nullptr){ value = std::string(ptr->valuestring);
    }
}

void json::find(const char *node, int & value) {
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    if(ptr != nullptr){
        value = ptr->valueint;
    }
}

void json::find(const char *node, const char *subnode, std::string &value) {
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    if(ptr != nullptr) {
        cJSON *sub_ptr = cJSON_GetObjectItem(ptr, subnode);
        if(sub_ptr != nullptr)
            value = std::string(sub_ptr->valuestring);
    }else{
        printp("Can't find node,Please check your json config\n");
    }
}

void json::find(const char *node, const char *subnode, int &value) {
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    if(ptr != nullptr) {
        cJSON *sub_ptr = cJSON_GetObjectItem(ptr, subnode);
        if(sub_ptr != nullptr)
            value = sub_ptr->valueint;
    }
}


void json::array(const char *node,const char* subnode,std::vector<std::string> &res){
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    cJSON* tmp,*sub_ptr;

    sub_ptr = cJSON_GetObjectItem(ptr,subnode);

    if(ptr == nullptr || sub_ptr == nullptr){
        printp("Not Find Array node ... ... \n");
        exit(0);
    }

    int32_t size = cJSON_GetArraySize(sub_ptr);

    for(int32_t i = 0 ; i < size ; i++){
        tmp = cJSON_GetArrayItem(sub_ptr,i);
        res.push_back(std::string(tmp->valuestring));
    }
}

void json::array(const char* node,std::vector<std::string> &res){
    cJSON* ptr = cJSON_GetObjectItem(root,node);
    cJSON* tmp;
    if(ptr == nullptr){
        printp("Not Find Array node ... ... \n");
        exit(0);
    }

    int32_t size = cJSON_GetArraySize(ptr);

    for(int32_t i = 0 ; i < size ; i++){
        tmp = cJSON_GetArrayItem(ptr,i);
        res.push_back(std::string(tmp->valuestring));
    }
}
